package com.amos.knife4j.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


import com.amos.knife4j.tool.ConvertUtils;
import com.amos.knife4j.config.exception.service.ServiceExceptionHandler;
import com.amos.knife4j.config.result.ResultEnums;
import com.amos.knife4j.config.exception.BusinessException;

import com.amos.knife4j.dao.DicDao;
import com.amos.knife4j.entity.Dic;
import com.amos.knife4j.dto.form.DicForm;
import com.amos.knife4j.dto.DicBean;
import com.amos.knife4j.service.DicService;
/** 
 * <br/>
 * Created by amos on 2021/09/17
 */
@Service
public class DicServiceImpl extends BaseServiceImpl<Dic, String> implements DicService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private DicDao dicDao;

    @Override
    @Transactional
    @ServiceExceptionHandler
    public void insert(String userId, DicForm form) {
        //转换
        Dic dic = form.convertDO();
        //初始赋值
        String id=IdUtil.simpleUUID();
        dic.setId(id);
        dic.setCreateUser(userId);
        dic.setUpdateUser(userId);
        insertSelective(dic);
        //图片处理


    }

    @Override
    @Transactional
    @ServiceExceptionHandler
    public void update(String id,String userId, DicForm form) {
        //获取原元素
        Dic old = selectByPrimaryKey(id);
        if (old == null) {
            throw new BusinessException(ResultEnums.OBJECT_NOT_EXISTS);
        }
        //赋值
        Dic dic = form.convertDO();
        dic.setId(id);
        dic.setUpdateUser(userId);
        dicDao.update(dic);
        //图片处理
    }

    @Override
    @Transactional
    @ServiceExceptionHandler
    public void updateState(String id,String userId, String state){
        dicDao.updateState(id,state,userId);
    }

    @Override
    @Transactional
    @ServiceExceptionHandler
    public void delete(String id) {
       Dic old = selectByPrimaryKey(id);
       deleteByPrimaryKey(id);
        //图片删除

    }

    @Override
    @ServiceExceptionHandler
    public PageInfo<DicBean> selectDicPage(int pageNum, int pageSize) {
        Dic ec = new Dic();
        Dic lc = new Dic();
        PageInfo<Dic> pages = selectByPage(ec, lc, pageSize, pageNum, "create_time ", true);
        PageInfo<DicBean> pageInfo = new ConvertUtils().convertPage(pages,DicBean::new );
        return pageInfo;
    }

    @Override
    @ServiceExceptionHandler
    public DicBean selectDicDetail(String id) {
        Dic dic = selectByPrimaryKey(id);
        if (dic == null) {
            throw new BusinessException(ResultEnums.OBJECT_NOT_EXISTS);
        }
        DicBean dicBean = new DicBean(dic);
        return dicBean;
    }
}